package com.prs.crm.dao.sys.impl;

import java.util.Collection;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.dao.sys.FormDao;
import com.prs.crm.domain.sys.Form;
import com.prs.crm.domain.sys.FormField;

public class FormDaoImpl extends BaseDaoImpl<Form> implements FormDao {

	
	@SuppressWarnings("unchecked")
	public Integer getMaxSequence(final Form parent)
	{
		return (Integer)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
						public Object doInHibernate(Session session) throws HibernateException {
				        	Criteria criteria = session.createCriteria(FormField.class);
				        	criteria.add(Restrictions.eq("parent", parent));
				        	criteria.setProjection(Projections.max("sequence"));
				        	return criteria.uniqueResult();
				        }   
				 } );
	}
	@SuppressWarnings("unchecked")
	public 	Collection<Form> getAllForm()
	{
		return (Collection<Form>)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
						public Object doInHibernate(Session session) throws HibernateException {
				        	Criteria criteria = session.createCriteria(Form.class);
				        	return criteria.list();
				        }   
				 } );
	}
	
	public Form findByClassName(final String className)
	{
		return (Form)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
						@SuppressWarnings("unchecked")
						public Object doInHibernate(Session session) throws HibernateException {
				        	Criteria criteria = session.createCriteria(Form.class);
				        	criteria.add(Restrictions.eq("className", className));
				        	List<Form> result = criteria.list();
				        	if (result.size()>0)
				        	{
				        		return result.get(0);
				        	}
				        	else
				        	{
				        		return null;
				        	}
				        	
				        }   
				 } );
	}
	@Override
	public Form findByEname(final String ename) {
		Criteria criteria=this.getSession().createCriteria(Form.class);
		criteria.add(Restrictions.eq("ename", ename));
		List result=criteria.list();
		if (result==null || result.size()==0) {
			return null;
		}
		return (Form) criteria.list().get(0);
	}
}
